// 导入 Eachars 组件
import echarts from 'echarts'
import _ from 'lodash'
export default {
  data() {

    return {
      websock: null,
      path: "wss://www.chayiweilai.com/websocket=cywl",
      socket: "",
      message: '',
      kfToken: '',
      msgList: [],
      userId: '',
      token: '',
      number: 0,



    
    }
  },
  
  mounted() {
    // 初始化
    this.init()
  },
  created() {

  },
  destroyed() {
    // 销毁监听
    this.socket.onclose = this.close
  },
  methods: {
    chat() {
      this.getData();
    },
    async refreshData() {
      const { data: res } = await this.$http.post('/manage/getAllUserSizes', {})//, { params: this.queryinfo }

      console.log(res);
      this.number = res.data;
    },
    init() {
      if (typeof (WebSocket) === "undefined") {
        alert("您的浏览器不支持socket")
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    open() {
      console.log("socket连接成功")

    },
    error() {
      console.log("连接错误")
    },
    getMessage(msg) {
      console.log(typeof(msg.data));
      console.log(msg.data,msg.data.indexOf('cywl')==-1)
      if (msg.data.indexOf('cywl')==-1) {
        // obj.msg.content.text= msg.data.split('#')[1];
        let obj = {
          type: 1,
          message:JSON.parse(msg.data).message
        }
        this.msgList.push(obj);
      } else {
        this.token = msg.data;
        //this.getData();
        this.refreshData();
        this.kfToken = msg.data;
      }
    },
    async getData(data) {
      const { data: res } = await this.$http.post('/manage/getFirstUsers', { queryString: this.token })//, { params: this.queryinfo }

      console.log(res);
      this.userId = res.data.userId;
    },
    sendMessage() {
      //console.log(this.message);
      let data = this.kfToken + ',' + this.userId + '#' + this.message;
      console.log(data);
      let obj = {
        type: 2,
        message: this.message
      }
      this.msgList.push(obj);
      this.socket.send(data)
    },
    close() {
      console.log("socket已经关闭")
    }
  }
}
